import { readBody, defineEventHandler } from 'h3'
import { randomUUID } from 'crypto'
import { query } from '../util/mysql'
import { recordLog } from '../util/log'
import type { PayMsgDto } from '../types/payinfo'

// POST /api/savemsg
// 验证入参中的 Authorize 字段等于 'pzlpzlpzl'，并且 Msg 包含 '微信支付收款' 时，
// 将记录插入 lin_payinfo 表。

export default defineEventHandler(async (event) => {
  try {
    const body = (await readBody(event)) as PayMsgDto | any

    const authorize = body?.Authorize ?? body?.authorize ?? ''
    const msg = body?.Msg ?? body?.msg ?? ''

    if (authorize !== 'pzlpzlpzl') {
      await recordLog(event as any, { message: 'savemsg: invalid authorize', userId: 0 })
      return 'fail'
    }

    if (!msg || typeof msg !== 'string' || msg.indexOf('微信支付收款') === -1) {
      await recordLog(event as any, { message: 'savemsg: msg missing or not contain 微信支付收款', userId: 0 })
      return 'fail'
    }

    const id = typeof randomUUID === 'function' ? randomUUID() : (Date.now().toString(36) + Math.random().toString(36).slice(2))
    const createTime = new Date()

    const sql = 'INSERT INTO lin_payinfo (id, message, create_time, is_deleted) VALUES (?, ?, ?, ?)'
    // is_deleted 存为 bit(1)，使用 0 表示未删除
    await query(sql, [id, msg, createTime, 0])
    await recordLog(event as any, { message: `savemsg: inserted payinfo id=${id}`, userId: 0 })
    return 'success'
  } catch (err: any) {
    event.node.res.statusCode = 500
    await recordLog(event as any, { message: `savemsg: internal error ${String(err)}`, userId: 0 })
    return { status: 500, message: 'internal error', error: String(err) }
  }
})
